/**
 * Package:com.goldcitynet.server.session;
 * $Id: UserIoSession.java,v 1.2 2009/03/24 03:36:59 yangc Exp $
 * Copyright(c) 2001-2005 www.afteryuan.com
 */
package com.afteryuan.server.mina;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.mina.core.session.IoSession;
import com.afteryuan.server.utils.Constants;
import com.afteryuan.server.ConnectSession;
import com.afteryuan.server.command.down.CommandDown;

/**
 * MinaConnectSession
 * ConnectSession的mina实现
 * <p/>
 * <p><a href="UserIoSession.java.html"><i>View Source</i></a></p>
 *
 * @author <a href="mailto:afteryuan@afteryuan.com">$Author: yangc $</a>
 * @version $Revision: 1.2 $
 */
public class MinaConnectSession implements ConnectSession {
    private static Log log = LogFactory.getLog(MinaConnectSession.class);
    /**
     * IoSession对象
     */
    private IoSession session;

    public MinaConnectSession(IoSession session) {
        this.session = session;
    }

    public void write(CommandDown message){
        try{
            session.write(message);
        }catch(Exception e){
            //流写入错误。查看session是否已经关闭。已经关闭则将用户移动到暂停用户表中。
            e.printStackTrace();
        }
    }

    public boolean isConnected() {
        return session.isConnected();
    }

    public boolean isClosed() {
        return session.isClosing();
    }

    public Object getAttribute(String key) {
        return session.getAttribute(key);
    }

    public void setAttribute(String key, Object value) {
        session.setAttribute(key,value);
    }

    public void removeAttribute(String key) {
        session.removeAttribute(key);
    }

    public String getKey() {
        return (String) session.getAttribute(Constants.SESSION_ID_KEY);
    }

    public void close() {
        //所有queue完成后关闭连接
        session.close(false);
    }

    public boolean isCurrentSession(IoSession ioSession){
        return session.equals(ioSession);
    }

    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;

        MinaConnectSession that = (MinaConnectSession) o;

        if (session != null ? !session.equals(that.session) : that.session != null) return false;

        return true;
    }

    public int hashCode() {
        return (session != null ? session.hashCode() : 0);
    }
}